package cn.edu.ldh.toolapp.slice;

import cn.edu.ldh.toolapp.ResourceTable;
import cn.edu.ldh.toolapp.entity.NoteItem;
import cn.edu.ldh.toolapp.provider.NoteItemProvider;
import cn.edu.ldh.toolapp.stores.NoteStore;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.data.DatabaseHelper;
import ohos.data.orm.OrmContext;
import ohos.data.orm.OrmPredicates;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import java.util.List;

public class NoteAbilitySlice extends AbilitySlice {
    private final static HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 1, "NoteAbilitySlice");
    static OrmContext ormContext;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_note);
        this.startInit();
        this.createDataBase();
        this.initListContainer();
    }

    private void startInit() {
        findComponentById(ResourceTable.Id_note_write_btn).setClickedListener(this::toWrite);
    }

    private void toWrite(Component component) {
        presentForResult(new AddNoteAbilitySlice(), new Intent(), 1);
    }

    //初始化列表和列表点击事件
    private void initListContainer() {
        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_note_list);
        List<NoteItem> list = getData();
        NoteItemProvider noteItemProvider = new NoteItemProvider(list, this);
        listContainer.setItemProvider(noteItemProvider);
        listContainer.setItemClickedListener((container, component, position, id) -> {
            NoteItem noteItem = (NoteItem) container.getItemProvider().getItem(position);
            Intent intent = new Intent();
            intent.setParam("noteItem", noteItem);
            present(new NoteDetailAbilitySlice(), intent);
        });
    }

    //初始化获取数据
    private List<NoteItem> getData() {
        return NoteStore.getInstance().getAllNote();
    }

    //创建数据库 若已有此数据库不会重复创建
    private void createDataBase() {
        NoteStore.getInstance().createDataBase(this);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
